package cn.wolfcode.luowowo.wesite.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.until.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.wesite.annotation.RequireLogin;
import cn.wolfcode.luowowo.wesite.annotation.UserParam;
import cn.wolfcode.luowowo.wesite.until.CookieUtil;
import cn.wolfcode.luowowo.wesite.until.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * Created by LENOVO on 2019/8/11.
 */

@Controller
@RequestMapping("travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private ITravelStatisRedisService travelStatisRedisService;

    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo") TravelQuery qo){

        model.addAttribute("pageInfo",travelService.query(qo));

        //最新游记的前十条

        List<TravelComment> numTop10 = travelCommentService.getNumTop10();
        model.addAttribute("tcs",numTop10);

        //查询所有的VO对象来
        model.addAttribute("vo",travelStatisRedisService.getTravelStatisVos(RedisKeys.TRAVEL_STATIS_VO.getPrefix()));
       /* List<TravelStatisVO> list=travelStatisRedisService.getTravelStatisVos(RedisKeys.TRAVEL_STATIS_VO.getPrefix());
        for(TravelStatisVO vo:list){
            System.out.println(vo.getTravelId());
        }*/
        return "travel/list";
    }

    @RequestMapping("/detail")
    public String detail(Model model,Long id,HttpServletRequest request,HttpServletResponse response){
        //通过id查询到游记明细，然后再查询内容在设置进去
        Travel detail = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        detail.setTravelContent(content);
        model.addAttribute("detail",detail);

        //相关目的地的查询
        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        //中国广东
        model.addAttribute("toasts",toasts);

        //广州
        model.addAttribute("dest",dest);

        //查询 关联目的地下面的前三个攻略
        List<StrategyDetail> sds = strategyDetailService.getViewNumTop3(detail.getDest().getId());
        model.addAttribute("sds",sds);

        //关联某个目的地下面游记
        List<Travel> ts = travelService.getTravelTop3(detail.getDest().getId());
        model.addAttribute("ts",ts);


        //判断登陆了才能编辑
        String token = CookieUtil.getToken(request);


        if(token !=null){
            UserInfo userInfo = userInfoRedisService.getUserByToken(token);
            model.addAttribute("userInfo",userInfo);
        }

        //先让游记列表显示

        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);//游记的id
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);

        Page page = travelCommentService.query(qo);
        model.addAttribute("list", page.getContent());

        //显示阅读数量加一
        travelStatisRedisService.viewNumIncrease(id,1);
        model.addAttribute("vo",travelStatisRedisService.getTravelStatisVo(id));


        return "travel/detail";
    }


    @RequestMapping("/input")
    public String input(Model model,Long id){
        if(id !=null){
            //通过id，查询一个游记
            Travel travel = travelService.get(id);
            //设置回显示的内容
            travel.setTravelContent(travelService.getContent(id));
            model.addAttribute("tv",travel);

        }

        model.addAttribute("dests",destinationService.getDestByDeep(3));
        return "travel/input";
    }



    @Value("${file.path}")
    private String filePath;

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @RequireLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object  saveOrUpdate(Travel travel ,@UserParam UserInfo userInfo){

        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);

        return AjaxResult.SUCCESS.addData(id);
    }



    @RequestMapping("/isLogin")
    @ResponseBody
    public Object  isLogin(HttpServletRequest request){
        //判断登陆了才能编辑
        String token = CookieUtil.getToken(request);


        if(token !=null){
            return  AjaxResult.SUCCESS;
        }
        return  AjaxResult.FAIL;
    }


    @RequestMapping("/commentAdd")
    public String commentAdd(Model model,TravelComment comment,int floor,@UserParam UserInfo userInfo,HttpServletRequest request){
        //添加评论
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setCity(userInfo.getCity());
        comment.setLevel(userInfo.getLevel());
        comment.setHeadUrl(userInfo.getHeadImgUrl());

        //返回最新的数据
        TravelComment travelComment = travelCommentService.saveOrUpdate(comment);

        model.addAttribute("c",travelComment);
        model.addAttribute("floor",floor+1);


        //评论加一的操作
        //增加一条评论数量
        travelStatisRedisService.replyNumIncrease(comment.getTravelId(),1);
        //int replynum = travelStatisRedisService.getTravelStatisVo(comment.getTravelId()).getReplynum();


        return "travel/commentTpl";
    }

    //评论是否登录判断
    @RequestMapping("/commmentLogin")
    @ResponseBody
    public Object commmentLogin(HttpServletRequest request){
        String token = CookieUtil.getToken(request);
        //没登录
        if (token ==null){
          return AjaxResult.SUCCESS;
        }
        return AjaxResult.FAIL;
    }




    //游记收藏的新增和取消
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long sid,@UserParam UserInfo userInfo){
        AjaxResult result=null;
        //表示没登陆，返回错误的代码 和错误信息
        if(userInfo==null){
            result=new AjaxResult(false,"请先登录，才能收藏");
            result.setCode(102);
            return result;
        }
        boolean ret = travelStatisRedisService.favor(sid, userInfo.getId());
        //返回结果，如果为成功就加上数量,,如果是取消收藏,也返回收藏的数量，但是错误结果为空
        return new AjaxResult(ret,"").addData(travelStatisRedisService.getTravelStatisVo(sid));
    }

    //游记顶的操作

    //攻略 顶的操作
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object strategyThumbup(Long sid,@UserParam UserInfo userInfo){
        AjaxResult result=null;
        //表示没登陆，返回错误的代码 和错误信息
        if(userInfo==null){
            result=new AjaxResult(false,"请先登录，在顶哦");
            result.setCode(102);
            return result;
        }

        //收藏和取消收藏的实现
        boolean ret = travelStatisRedisService.thumbup(sid, userInfo.getId());
        //返回结果，如果为成功就加上数量,,如果是取消收藏,也返回收藏的数量，但是错误结果为空
        return new AjaxResult(ret,"").addData(travelStatisRedisService.getTravelStatisVo(sid));

    }

}
